/**
 * Test d'un simple client serveur avec échange de messages sur UDP.
 */
#include "tests.h"
#include "commun/utilise_sdl.h"
#include "reseau/client_reseau.h"
#include "reseau/serveur_reseau.h"
#include "commun/instantane_du_piano.h"
#include "commun/sous_systeme.h"
#include "thread/thread.h"
#include "temps/minuterie.h"
#include <iostream>

namespace {
	struct cln : public thread_acteur {
		void executer() {
			client_reseau cl("localhost", 45049);
			std::cerr << "CLN Connecte." << std::endl;
			
			instantane_du_piano i, r;
			for(int k=0; k<instantane_du_piano::nombre_de_touches; k+=2)
				i[k] = true;
			
			std::cerr << "CLN Envoye " << i << std::endl;
			
			minuterie<> timeout(50000);
			do {
				cl.emetteur().envoyer_udp(i);
			} while(!cl.recepteur().recevoir_udp(r) && !timeout);
			
			if(timeout.depasse())
				std::cerr << "CLN Timeout" << std::endl;
			else
				std::cerr << "CLN Recu " << r << std::endl;
		}
	};
	struct srv : public thread_acteur {
		void executer() {
			instantane_du_piano i, e;
			serveur_reseau sr(45049);
			std::cout << "SRV En attente." << std::endl;
			
			while(!sr.occupe())
				sr.accepter_connexions();
			
			std::cout << "SRV Connecte, va envoyer " << e << std::endl;
			
			temps::attendre(1000);
			
			//e[1] = true;
			minuterie<> timeout(50000);
			do {
				sr.emetteur().envoyer_udp(e);
			} while(!sr.recepteur().recevoir_udp(i) && !timeout);
			
			if(timeout.depasse()) {
				std::cout << "SRV Timeout" << std::endl;
				return;
			}
			else
				std::cout << "SRV Recu " << i << std::endl;
		}
	};
}

void client_serveur() {
	using namespace std;
	module_sdl lancer_sdl;
	{
		module_reseau lancer_reseau;
		{
			cln c;
			srv s;
			thread tS(s);
			temps::attendre(1000);
			thread tC(c);		
		}
	}
	temps::attendre(1000);
}



/*
 Uint8 donnees[instantane_du_piano::nb_octets + sizeof(temps::type_temps)];
 temps::attendre(200);
 instantane_du_piano i;
 i[3] = true;
 cout << "Voici i = (data=" << i << ", timestamp=" << i.timestamp() << ")" << endl;
 cout << "Longueur du paquet : " << instantane_du_piano::nb_octets << " + " << sizeof(temps::type_temps) << " = " << sizeof(temps::type_temps) + i.remplir(donnees + sizeof(temps::type_temps), reinterpret_cast<temps::type_temps*>(donnees));
 cout << "Abracadabra..." << endl;
 temps::attendre(1000);
 instantane_du_piano z;
 z.initialiser(donnees + sizeof(temps::type_temps), *(reinterpret_cast<temps::type_temps*>(donnees)));
 cout << "Voici z = (data=" << z << ", timestamp=" << z.timestamp() << ")" << endl;
*/
